package com.jaiky.imagepicker;

import com.jaiky.imagepicker.imageloader.UilImageLoader;
import com.jaiky.imagepicker.util.Constant;
import com.jaiky.imagespickers.ImageItem;
import com.jaiky.imagespickers.ImagePicker;
import com.jaiky.imagespickers.ImageSelectorAbility;
import com.jaiky.imagespickers.camera.CameraPhotoAbility;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.security.SystemPermission;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static ohos.bundle.IBundleManager.PERMISSION_GRANTED;

public class MainAbility extends Ability {
    private ImagePicker imagePicker;
    private DirectionalLayout directionalLayout;
    private ArrayList<ImageItem> images = new ArrayList<>();
    private Text tv1;
    public static final int REQ_PERMISSION_CODE = 1001;

    private final List<String> mPermissions =
            new LinkedList<>(
                    Arrays.asList(
                            SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE));

    @Override
    public void onStart(Intent intent) {
        try {
            int color = getResourceManager().getElement(ResourceTable.Color_status_bar_color).getColor();
            getWindow().setStatusBarColor(color);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        directionalLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_llContainer);
        tv1 = (Text) findComponentById(ResourceTable.Id_tv1);
        ImageLoaderConfiguration config = ImageLoaderConfiguration.createDefault(this);
        ImageLoader.getInstance().init(config); // UniversalImageLoader初始化
        ImagePicker.setTakePhotoAbility(CameraPhotoAbility.class);
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new UilImageLoader()); // 设置图片加载器
        initImagePicker();
        findComponentById(ResourceTable.Id_btn2).setClickedListener(component -> {
            imagePicker.setMultiMode(true);
            imagePicker.setSelectLimit(9);
            reqPermissions();
        });
        findComponentById(ResourceTable.Id_btn1).setClickedListener(component -> {
            imagePicker.setMultiMode(true);
            imagePicker.setSelectLimit(1);
            reqPermissions();
        });

    }

    private void initImagePicker() {
        imagePicker.setCrop(false); // 允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); // 是否按矩形区域保存
        imagePicker.setFocusWidth(Constant.SEVENZORE); // 裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(Constant.SEVENZORE); // 裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(Constant.ONEQIAN); // 保存文件的宽度。单位像素
        imagePicker.setOutPutY(Constant.ONEQIAN); // 保存文件的高度。单位像素
        imagePicker.setContainer(directionalLayout, 4, true);
    }


    private void reqPermissions() {
        mPermissions.removeIf(perM -> verifySelfPermission(perM) == PERMISSION_GRANTED || !canRequestPermission(perM));
        if (!mPermissions.isEmpty()) {
            requestPermissionsFromUser(
                    mPermissions.toArray(new String[0]), REQ_PERMISSION_CODE);
        } else {
            choosePic();
        }
    }

    private void choosePic() {
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(ImageSelectorAbility.class.getName())
                .build();
        Intent intent = new Intent();
        intent.setOperation(operation);
        startAbilityForResult(intent, Constant.ONWZORE);
    }

    /**
     * 权限回调
     *
     * @param requestCode  requestCode
     * @param ss           ss
     * @param grantResults grantResults
     */
    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] ss, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, ss, grantResults);
        if (requestCode != 0) {
            choosePic();
            return;
        }
        boolean isHavePermission = false;
        for (int num = 0; num < ss.length; num++) {
            isHavePermission = grantResults[num] == PERMISSION_GRANTED;
        }
        if (isHavePermission) {
            restart();
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        if (resultData == null) {
            return;
        }
        images.clear();
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (resultCode == ImagePicker.REQUEST_CODE_PREVIEW
                || resultCode == ImagePicker.RESULT_CODE_ITEMS
                && requestCode == Constant.ONWZORE) {
            images = resultData.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS);
            tv1.setText("");
            for (int i = 0; i < images.size(); i++) {
                tv1.append(images.get(i).uriSchema);
                tv1.append("\n");
            }
        }

    }
}
